using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using GroupSix.Infrastructure.Data;
using GroupSix.Infrastructure.Reposoitories;
using GroupSix.Domain.Repositories;
using GroupSix.Domain.Services;
using GroupSix.Domain.Events;
using GroupSix.Infrastructure.Services;
using GroupSix.Application.Services;
using GroupSix.Application.Configuration;
using GroupSix.Infrastructure.Events;
using GroupSix.Api.Middleware;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//实现跨域
builder.Services.AddCors(options =>
{
     options.AddPolicy("AllowFrontend",
         policy => policy.WithOrigins(
                "http://localhost:5173",
                "http://localhost:5174", 
                "http://localhost:5175",
                "http://localhost:5176",
                "http://localhost:5177",
                "http://localhost:3000",
                "http://localhost:8080")
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials());
});

// 添加数据库服务
builder.Services.AddDbContext<GroupSixDbContext>(options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection"), 
        b => b.MigrationsAssembly("GroupSix.Infrastructure")));

// 添加仓储服务
builder.Services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IRoleRepository, RoleRepository>();
builder.Services.AddScoped<IMenuRepository, MenuRepository>();
builder.Services.AddScoped<ISystemSettingRepository, SystemSettingRepository>();
builder.Services.AddScoped<ISystemSettingLogRepository, SystemSettingLogRepository>();
builder.Services.AddScoped<IOperationLogRepository, OperationLogRepository>();
builder.Services.AddScoped<IArticleRepository, ArticleRepository>();

// 添加领域服务
builder.Services.AddScoped<IPasswordHasher, PasswordHasher>();

// 添加JWT服务
builder.Services.AddScoped<ITokenService>(provider => 
    new TokenService(
        builder.Configuration["Jwt:SecretKey"] ?? "your-secret-key-here",
        builder.Configuration["Jwt:Issuer"] ?? "GroupSix",
        builder.Configuration["Jwt:Audience"] ?? "GroupSix",
        provider.GetRequiredService<IUserRepository>()
    ));

// 添加JWT认证
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"] ?? "GroupSix",
            ValidAudience = builder.Configuration["Jwt:Audience"] ?? "GroupSix",
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration["Jwt:SecretKey"] ?? "your-secret-key-here"))
        };
    });

// 添加授权
builder.Services.AddAuthorization();

// 添加领域事件分发器
builder.Services.AddScoped<IDomainEventDispatcher, DomainEventDispatcher>();

// 添加应用服务
builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<RoleService>();
builder.Services.AddScoped<MenuService>();
builder.Services.AddScoped<PermissionService>();
builder.Services.AddScoped<FileService>();
builder.Services.AddScoped<SystemSettingService>();
builder.Services.AddScoped<OperationLogService>();
builder.Services.AddScoped<ArticleService>();

// 添加控制器
builder.Services.AddControllers();

// 添加文件上传配置
builder.Services.Configure<FileUploadOptions>(builder.Configuration.GetSection("FileUpload"));

var app = builder.Build();

// 初始化数据库种子数据
using (var scope = app.Services.CreateScope())
{
    var context = scope.ServiceProvider.GetRequiredService<GroupSixDbContext>();
    var passwordHasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher>();
    await DbInitializer.InitializeAsync(context, passwordHasher);
}

// 启用CORS策略
app.UseCors("AllowFrontend");

// 配置静态文件服务
app.UseStaticFiles();

app.UseRouting();

// 添加JWT认证和授权中间件
app.UseAuthentication();
app.UseAuthorization();

// 添加操作日志中间件（自动记录所有API操作）
app.UseOperationLogMiddleware();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

// 添加路由
app.MapControllers();

// 添加权限中间件（暂时注释，先测试基本功能）
// app.UsePermissionMiddleware();

app.Run();


